package com.mt.vsphere.core.conf;


import com.mt.vsphere.core.bean.ConfFieldType;
import com.mt.vsphere.core.util.ConfUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class NormalGameConf implements BaseGameConf {

    SysConfDao confDao;
    private Map<String,Object> confMap = new HashMap<>();

    @Override
    public void updateSysConf(String key, String value) {
        confMap.put(key,changeValueType(key, value));
        confDao.updateGameConfByKey(key,value);
    }

    @Override
    public <T> T getSysConf(String key) {
        return (T)confMap.get(key);
    }


    @Override
    public void reloadSysConf() {
        List<SysConf> confList = (List<SysConf>) confDao.findAll();
        for (SysConf sysConf:confList){
                confMap.put(sysConf.getName(),changeValueType(sysConf.getName(),sysConf.getValue()));
            }
    }

    @Override
    public void initSysConf() {
        List<SysConf> gameConfList = (List<SysConf>) confDao.findAll();

        //初始化配置 如果没有配置就在系统变量中找初始化值
        Map<String,String> defaultMap = getDefaultConf();
        for (SysConf sysConf:gameConfList){
             if (defaultMap.get(sysConf.getName()) != null){
                 confMap.put(sysConf.getName(),changeValueType(sysConf.getName(),sysConf.getValue()));
                 defaultMap.remove(sysConf.getName());
             }
        }

        defaultMap.forEach((key,value)->{
            confDao.save(getDefaultConfByKey(key));
            confMap.put(key,changeValueType(key,value));
        });

    }

    private Object changeValueType(String key,String value){
        SysConf sysConf = SysConfKey.valueOf(key).getSysConf();
        ConfFieldType filedType = ConfFieldType.valueOf(sysConf.getFieldType());
        return ConfUtil.changeValueType(filedType,value,sysConf.getCls());
    }

    protected abstract Map<String,String> getDefaultConf();

    protected abstract SysConf getDefaultConfByKey(String key);

}
